package com.car.exception;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import freemarker.core.Environment;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

public class FreemarkerExceptionHandler implements TemplateExceptionHandler {
	private static final Logger logger = Logger
	.getLogger(FreemarkerExceptionHandler.class);
	public void handleTemplateException(TemplateException te, Environment env, Writer out ) throws TemplateException {
		try {
			HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
					.getRequestAttributes()).getRequest();
			
			HttpServletResponse response = (HttpServletResponse)request.getAttribute("response_req");
			//request.setAttribute("msg", te.getMessage());
			logger.error(te.getMessage());
			if(!response.isCommitted()){
				response.sendRedirect("/error.htm");
			}
			return;
		} catch (IOException e) {
			logger.error("Failed to print error message. Cause: " + e.getMessage());
			return;
		}
	}

}
